package com.moyu.crowdsource.controller;

import com.moyu.crowdsource.entity.Address;
import com.moyu.crowdsource.service.AddressService;
import com.moyu.crowdsource.util.CommonErrorHandle;
import com.moyu.crowdsource.util.Msg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Api(
        value = "地址controller",
        tags = {"地址操作接口"}
)
@RestController
@RequestMapping("${api.base}/address")
public class AddressController {

    @Autowired
    AddressService addressService;

    @ApiOperation("添加地址")
    @PostMapping("/addaddress")
    public Msg addAddress(@Valid Address address, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return Msg.fail().add("errorFields", CommonErrorHandle.getErrorInfo(bindingResult));
        }
        addressService.addAddress(address);
        return Msg.success().add("info","地址添加成功");
    }

    @ApiOperation("删除地址")
    @DeleteMapping("/deladdress/{addressId}")
    public Msg delAddress(@PathVariable("addressId") String addressId){
        addressService.delAddress(addressId);
        return Msg.success().addInfo("删除地址成功");
    }

    @ApiOperation("地址查询")
    @GetMapping("/getaddress/{userId}")
    public Msg getAddress(@PathVariable("userId") Integer userId){
        return Msg.success().add("addresses",addressService.getUserAddress(userId));
    }

    @ApiOperation("地址更新")
    @PutMapping("/updateaddress/{addressId}")
    public Msg update(Address address){
        addressService.updateAddress(address);
        return Msg.success().addInfo("更新成功");
    }
}
